package com.store.common;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;

import java.sql.*;

/**
 * @author mmzhang
 * @date 2021年08月18日 20:06
 * @Description: 数据库工具
 */
public abstract class DBUtils {

    public static Connection initData() {
        Connection conn = null;
        // 加载HSQLDB驱动
        try {
            Class.forName("org.hsqldb.jdbcDriver");
            conn = DriverManager.getConnection("jdbc:hsqldb:mem:mybatis", "sa", "");
//            使用mybatis的scriptRunner工具类执行数据库脚本
            ScriptRunner scriptRunner=new ScriptRunner(conn);
//            不输出sql日志
            scriptRunner.setLogWriter(null);
            scriptRunner.runScript(Resources.getResourceAsReader("hsqldb/create-table.sql"));
            scriptRunner.runScript(Resources.getResourceAsReader("hsqldb/init-data.sql"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }


    /**
     * 打印列名称和列值
     * @param resultSet
     * @throws SQLException
     */
    public static void dumpRS(ResultSet resultSet) throws SQLException {
        ResultSetMetaData metaData=resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        while (resultSet.next()){
            for (int i = 0; i < columnCount; i++) {
                String columnName = metaData.getColumnName(i);
                String columnVal = resultSet.getString(columnName);
                System.out.println(columnName+":"+columnVal);
            }
            System.out.println("---------------------------------");
        }

    }












}
